<!--
  编辑器工作区主组件
  重构后的模块化编辑器
-->
<template>
  <div class="editor-workspace">
    <!-- 工具栏 -->
    <EditorToolbar
      :header-drawer-visible="headerDrawerVisible"
      @save="handleSave"
      @export="handleExport"
      @undo="handleUndo"
      @redo="handleRedo"
      @toggle-header-drawer="toggleHeaderDrawer"
    />
    
    <!-- 主要工作区 -->
    <div class="workspace-main">
      <!-- 左侧面板 -->
      <div class="workspace-sidebar left" :style="{ width: `${leftSidebarWidth}px` }">
        <AssetLibrary />
        <div class="sidebar-resizer left" @mousedown="startResize('left', $event)"></div>
      </div>
      
      <!-- 中央画布区域 -->
      <div class="workspace-center">
        <EditorCanvas 
          ref="canvasRef"
          @layer-select="handleLayerSelect"
          @layer-transform="handleLayerTransform"
        />
      </div>
      
      <!-- 右侧面板 -->
      <div class="workspace-sidebar right" :style="{ width: `${rightSidebarWidth}px` }">
        <div class="sidebar-resizer right" @mousedown="startResize('right', $event)"></div>
        <PropertiesPanel />
      </div>
    </div>
    
    <!-- 底部时间轴 -->
    <div class="workspace-timeline" :style="{ height: `${timelineHeight}px` }">
      <div class="timeline-resizer" @mousedown="startResize('timeline', $event)"></div>
      <EditorTimeline
        @keyframe-add="handleKeyframeAdd"
        @keyframe-update="handleKeyframeUpdate"
        @keyframe-delete="handleKeyframeDelete"
        @time-change="handleTimeChange"
        @clip-update="handleClipUpdate"
      />
    </div>

    <!-- 顶部工具栏抽屉 -->
    <n-drawer
      v-model:show="headerDrawerVisible"
      placement="right"
      :width="360"
      :trap-focus="false"
      display-directive="show"
    >
      <n-drawer-content title="顶部工具栏">
        <template #header>
          <div class="drawer-header">
            <div class="header-title">顶部工具栏</div>
          </div>
        </template>

        <div class="header-tools-container">
          <!-- 导航面包屑 -->
          <div class="tool-section">
            <div class="section-title">
              <n-text strong>导航</n-text>
            </div>
            <div class="breadcrumb-section">
              <n-breadcrumb>
                <n-breadcrumb-item>
                  <router-link to="/">首页</router-link>
                </n-breadcrumb-item>
                <n-breadcrumb-item>
                  <router-link to="/workspace/editor">工作区</router-link>
                </n-breadcrumb-item>
              </n-breadcrumb>
            </div>
          </div>

          <!-- 主题和通知 -->
          <div class="tool-section">
            <div class="section-title">
              <n-text strong>系统控制</n-text>
            </div>
            <div class="tool-buttons">
              <n-button block secondary @click="toggleTheme">
                <template #icon>
                  <n-icon>
                    <MoonOutline v-if="isDarkMode" />
                    <SunnyOutline v-else />
                  </n-icon>
                </template>
                {{ isDarkMode ? '切换亮色模式' : '切换暗色模式' }}
              </n-button>

              <n-button block secondary @click="openNotifications">
                <template #icon>
                  <n-icon><NotificationsOutline /></n-icon>
                </template>
                通知中心
                <n-badge
                  v-if="unreadCount > 0"
                  :value="unreadCount"
                  :max="99"
                  style="margin-left: auto;"
                />
              </n-button>

              <n-button block secondary @click="openHelp">
                <template #icon>
                  <n-icon><HelpCircleOutline /></n-icon>
                </template>
                帮助中心
              </n-button>
            </div>
          </div>
        </div>
      </n-drawer-content>
    </n-drawer>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  NDrawer,
  NDrawerContent,
  NText,
  NButton,
  NIcon,
  NBreadcrumb,
  NBreadcrumbItem,
  NBadge
} from 'naive-ui'
import {
  MoonOutline,
  SunnyOutline,
  NotificationsOutline,
  HelpCircleOutline
} from '@vicons/ionicons5'
import { useEditorStore } from '../../stores/editor'
import { useAppStore } from '../../stores/appStore'
import { animationEngine } from '../../core/engine/animation'
import { message } from '../../utils/message'

// 组件导入
import EditorToolbar from './EditorToolbar.vue'
import AssetLibrary from './AssetLibrary.vue'
import EditorCanvas from './EditorCanvas.vue'
import PropertiesPanel from './PropertiesPanel.vue'
import EditorTimeline from './EditorTimeline.vue'


// 状态管理
const router = useRouter()
const editorStore = useEditorStore()
const appStore = useAppStore()

// 组件引用
const canvasRef = ref<InstanceType<typeof EditorCanvas> | null>(null)

// 面板尺寸
const leftSidebarWidth = ref(280)
const rightSidebarWidth = ref(280)
const timelineHeight = ref(200)

// 顶部工具栏抽屉状态
const headerDrawerVisible = ref(false)

// 拖拽调整尺寸
const resizeState = ref<{
  isResizing: boolean
  type: 'left' | 'right' | 'timeline'
  startX: number
  startY: number
  startWidth: number
  startHeight: number
} | null>(null)

// 事件处理器
const handleSave = async () => {
  try {
    await editorStore.saveProject()
    message.success('项目保存成功')
  } catch (error) {
    message.error('项目保存失败')
    console.error('保存失败:', error)
  }
}

const handleExport = () => {
  // TODO: 实现导出功能
  message.info('导出功能开发中...')
}

const handleUndo = () => {
  // TODO: 实现撤销功能
  message.info('撤销功能开发中...')
}

const handleRedo = () => {
  // TODO: 实现重做功能
  message.info('重做功能开发中...')
}

const toggleHeaderDrawer = () => {
  headerDrawerVisible.value = !headerDrawerVisible.value
}

// 计算属性
const isDarkMode = computed(() => {
  return appStore.isDarkTheme
})

const unreadCount = computed(() => {
  return appStore.notifications.filter(n => !n.read).length
})

// 主题和通知方法
const toggleTheme = () => {
  appStore.toggleTheme()
}

const openNotifications = () => {
  // TODO: 打开通知抽屉
  message.info('通知功能开发中...')
}

const openHelp = () => {
  window.open('https://help.example.com', '_blank')
}

const handleLayerSelect = (layerId: string, multiSelect: boolean = false) => {
  editorStore.selectLayer(layerId, multiSelect)
}

const handleLayerTransform = (layerId: string, transform: any) => {
  editorStore.updateLayer(layerId, transform)
}

const handleKeyframeAdd = (trackId: string, time: number) => {
  const track = editorStore.tracks.find(t => t.id === trackId)
  if (!track) return
  
  const layer = editorStore.layers.find(l => l.id === track.layerId)
  if (!layer) return
  
  editorStore.addKeyframe(trackId, {
    time,
    value: {
      position: { ...layer.position },
      scale: { ...layer.scale },
      rotation: layer.rotation,
      opacity: layer.opacity
    }
  })
}

const handleKeyframeUpdate = (trackId: string, keyframeId: string, updates: any) => {
  editorStore.updateKeyframe(trackId, keyframeId, updates)
}

const handleKeyframeDelete = (trackId: string, keyframeId: string) => {
  editorStore.removeKeyframe(trackId, keyframeId)
}

const handleTimeChange = (time: number) => {
  editorStore.seekTo(time)
  updateLayersAtCurrentTime()
}

const handleClipUpdate = (trackId: string, clipId: string, data: { startTime: number; endTime: number }) => {
  console.log('📝 EditorWorkspace 收到片段更新:', {
    trackId,
    clipId,
    newStartTime: data.startTime,
    newEndTime: data.endTime,
    currentTotalDuration: editorStore.playback.totalDuration
  })

  // 找到对应的轨道
  const track = editorStore.tracks.find(t => t.id === trackId)
  if (track && track.clips) {
    // 找到对应的片段
    const clip = track.clips.find(c => c.id === clipId)
    if (clip) {
      console.log('📝 更新前的片段数据:', {
        oldStartTime: clip.startTime,
        oldEndTime: clip.endTime
      })

      // 更新片段数据
      clip.startTime = data.startTime
      clip.endTime = data.endTime

      console.log('✅ 片段数据更新完成:', {
        newStartTime: clip.startTime,
        newEndTime: clip.endTime
      })

      // 自动更新总时长 - 计算所有轨道中最晚结束的时间
      let maxEndTime = 0
      editorStore.tracks.forEach(track => {
        if (track.clips) {
          track.clips.forEach(clip => {
            maxEndTime = Math.max(maxEndTime, clip.endTime)
          })
        }
      })

      // 如果最大结束时间超过当前总时长，自动扩展
      if (maxEndTime > editorStore.playback.totalDuration) {
        const oldDuration = editorStore.playback.totalDuration
        editorStore.playback.totalDuration = maxEndTime
        console.log('🔄 自动扩展时间轴总时长:', {
          oldDuration,
          newDuration: maxEndTime,
          expandedBy: maxEndTime - oldDuration
        })
      }

    } else {
      console.log('❌ 找不到要更新的片段:', clipId)
    }
  } else {
    console.log('❌ 找不到轨道或轨道没有片段:', trackId)
  }
}

const handlePlay = () => {
  editorStore.play()
  startAnimationLoop()
}

const handlePause = () => {
  editorStore.pause()
  stopAnimationLoop()
}

const handleStop = () => {
  editorStore.stop()
  stopAnimationLoop()
  updateLayersAtCurrentTime()
}

// 动画循环
let animationLoopId: number | null = null

const startAnimationLoop = () => {
  if (animationLoopId) return
  
  const loop = () => {
    if (!editorStore.playback.isPlaying) return
    
    // 更新时间
    const deltaTime = 16 // 假设60fps
    const newTime = editorStore.playback.currentTime + (deltaTime / 1000) * editorStore.playback.playbackSpeed
    
    if (newTime >= editorStore.playback.totalDuration) {
      if (editorStore.playback.loop) {
        editorStore.seekTo(0)
      } else {
        editorStore.stop()
        return
      }
    } else {
      editorStore.seekTo(newTime)
    }
    
    updateLayersAtCurrentTime()
    animationLoopId = requestAnimationFrame(loop)
  }
  
  animationLoopId = requestAnimationFrame(loop)
}

const stopAnimationLoop = () => {
  if (animationLoopId) {
    cancelAnimationFrame(animationLoopId)
    animationLoopId = null
  }
}

// 更新图层到当前时间的状态
const updateLayersAtCurrentTime = () => {
  const currentTime = editorStore.playback.currentTime
  
  for (const layer of editorStore.layers) {
    const animatedProperties = animationEngine.calculateLayerPropertiesAtTime(
      layer, 
      editorStore.tracks, 
      currentTime
    )
    
    if (Object.keys(animatedProperties).length > 0) {
      editorStore.updateLayer(layer.id, animatedProperties)
    }
  }
  
  // 通知画布重新渲染
  canvasRef.value?.render()
}

// 面板尺寸调整
const startResize = (type: 'left' | 'right' | 'timeline', event: MouseEvent) => {
  event.preventDefault()
  
  resizeState.value = {
    isResizing: true,
    type,
    startX: event.clientX,
    startY: event.clientY,
    startWidth: type === 'left' ? leftSidebarWidth.value : 
                type === 'right' ? rightSidebarWidth.value : 0,
    startHeight: type === 'timeline' ? timelineHeight.value : 0
  }
  
  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
}

const handleResize = (event: MouseEvent) => {
  if (!resizeState.value) return
  
  const { type, startX, startY, startWidth, startHeight } = resizeState.value
  
  if (type === 'left') {
    const deltaX = event.clientX - startX
    leftSidebarWidth.value = Math.max(200, Math.min(400, startWidth + deltaX))
  } else if (type === 'right') {
    const deltaX = event.clientX - startX
    rightSidebarWidth.value = Math.max(200, Math.min(400, startWidth - deltaX))
  } else if (type === 'timeline') {
    const deltaY = event.clientY - startY
    timelineHeight.value = Math.max(150, Math.min(400, startHeight - deltaY))
  }
}

const stopResize = () => {
  resizeState.value = null
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
}

// 生命周期
onMounted(() => {
  // 初始化编辑器
  initializeEditor()
  updateLayersAtCurrentTime()
})

// 初始化编辑器数据
const initializeEditor = () => {
  // 避免重复初始化
  if (editorStore.layers.length > 0) {
    return
  }

  // 清除所有选择
  editorStore.clearSelection()

  // 添加示例图层
  const layer1 = editorStore.addLayer({
    name: '背景图层',
    visible: true,
    locked: false,
    type: 'image',
    position: { x: 400, y: 300 },
    scale: { x: 1, y: 1 },
    rotation: 0,
    opacity: 100
  })

  const layer2 = editorStore.addLayer({
    name: '角色图层',
    visible: true,
    locked: false,
    type: 'character',
    position: { x: 200, y: 200 },
    scale: { x: 1, y: 1 },
    rotation: 0,
    opacity: 100
  })

  // 为每个图层添加轨道
  const track1 = editorStore.addTrack({
    name: '背景动画',
    type: 'transform',
    layerId: layer1.id,
    visible: true,
    locked: false,
    keyframes: [],
    clips: [
      {
        id: 'clip-1',
        name: '背景片段1',
        startTime: 0,
        endTime: 5,
        assetId: 'scene-1'
      },
      {
        id: 'clip-2',
        name: '背景片段2',
        startTime: 5,
        endTime: 15,
        assetId: 'scene-1'
      }
    ]
  })

  const track2 = editorStore.addTrack({
    name: '角色动画',
    type: 'transform',
    layerId: layer2.id,
    visible: true,
    locked: false,
    keyframes: [],
    clips: [
      {
        id: 'clip-3',
        name: '角色片段1',
        startTime: 2,
        endTime: 18,
        assetId: 'char-1'
      }
    ]
  })



  // 添加一些示例关键帧
  editorStore.addKeyframe(track1.id, {
    time: 0,
    value: {
      position: { x: 400, y: 300 },
      scale: { x: 1, y: 1 },
      rotation: 0,
      opacity: 100
    },
    easing: 'ease-in-out'
  })

  editorStore.addKeyframe(track1.id, {
    time: 2,
    value: {
      position: { x: 500, y: 300 },
      scale: { x: 1.2, y: 1.2 },
      rotation: 10,
      opacity: 80
    },
    easing: 'ease-in-out'
  })

  editorStore.addKeyframe(track2.id, {
    time: 0,
    value: {
      position: { x: 200, y: 200 },
      scale: { x: 1, y: 1 },
      rotation: 0,
      opacity: 100
    },
    easing: 'linear'
  })

  editorStore.addKeyframe(track2.id, {
    time: 3,
    value: {
      position: { x: 600, y: 200 },
      scale: { x: 1, y: 1 },
      rotation: 360,
      opacity: 100
    },
    easing: 'ease-out'
  })

  // 添加更多关键帧来展示动态时长计算
  editorStore.addKeyframe(track1.id, {
    time: 8,
    value: {
      position: { x: 300, y: 400 },
      scale: { x: 0.8, y: 0.8 },
      rotation: -15,
      opacity: 90
    },
    easing: 'ease-in-out'
  })

  editorStore.addKeyframe(track2.id, {
    time: 12,
    value: {
      position: { x: 100, y: 400 },
      scale: { x: 1.5, y: 1.5 },
      rotation: 720,
      opacity: 80
    },
    easing: 'ease-in'
  })

  // 总时长将自动根据轨道内容计算

  // 添加示例素材
  editorStore.assets.characters.push(
    {
      id: 'char-1',
      name: '主角小明',
      type: 'character',
      category: '角色',
      path: '/assets/characters/xiaoming.png',
      url: 'https://via.placeholder.com/150x200/ff6b6b/ffffff?text=小明',
      thumbnail: 'https://via.placeholder.com/100x100/ff6b6b/ffffff?text=小明',
      size: 1024000,
      resolution: { width: 150, height: 200 },
      tags: ['主角', '男性', '学生'],
      description: '故事的主角，一个活泼的小学生',
      author: '系统',
      version: '1.0.0',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      license: {
        type: 'free',
        commercial: true,
        attribution: false
      }
    },
    {
      id: 'char-2',
      name: '小红',
      type: 'character',
      category: '角色',
      path: '/assets/characters/xiaohong.png',
      url: 'https://via.placeholder.com/150x200/4ecdc4/ffffff?text=小红',
      thumbnail: 'https://via.placeholder.com/100x100/4ecdc4/ffffff?text=小红',
      size: 1024000,
      resolution: { width: 150, height: 200 },
      tags: ['配角', '女性', '学生'],
      description: '小明的好朋友',
      author: '系统',
      version: '1.0.0',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      license: {
        type: 'free',
        commercial: true,
        attribution: false
      }
    }
  )

  editorStore.assets.scenes.push(
    {
      id: 'scene-1',
      name: '教室场景',
      type: 'scene',
      category: '场景',
      path: '/assets/scenes/classroom.jpg',
      url: 'https://via.placeholder.com/800x600/95a5a6/ffffff?text=教室',
      thumbnail: 'https://via.placeholder.com/200x150/95a5a6/ffffff?text=教室',
      size: 2048000,
      resolution: { width: 800, height: 600 },
      tags: ['室内', '学校', '教育'],
      description: '明亮的小学教室',
      author: '系统',
      version: '1.0.0',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      license: {
        type: 'free',
        commercial: true,
        attribution: false
      }
    }
  )
}

onBeforeUnmount(() => {
  stopAnimationLoop()
  stopResize()
})
</script>

<style lang="scss" scoped>
.editor-workspace {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  background-color: var(--body-color);
}

.workspace-main {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.workspace-sidebar {
  position: relative;
  background-color: var(--card-color);
  border: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  
  &.left {
    border-right: none;
  }
  
  &.right {
    border-left: none;
  }
}

.workspace-center {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.workspace-timeline {
  position: relative;
  background-color: var(--card-color);
  border-top: 1px solid var(--border-color);
}

.sidebar-resizer {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 4px;
  cursor: col-resize;
  background: transparent;
  z-index: 10;
  
  &.left {
    right: -2px;
  }
  
  &.right {
    left: -2px;
  }
  
  &:hover {
    background: var(--primary-color);
    opacity: 0.3;
  }
}

.timeline-resizer {
  position: absolute;
  top: -2px;
  left: 0;
  right: 0;
  height: 4px;
  cursor: row-resize;
  background: transparent;
  z-index: 10;
  
  &:hover {
    background: var(--primary-color);
    opacity: 0.3;
  }
}

// 顶部工具栏抽屉样式
.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;

  .header-title {
    font-size: 16px;
    font-weight: 600;
  }
}

.header-tools-container {
  padding: 16px 0;
}

.tool-section {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }

  .section-title {
    margin-bottom: 12px;
    padding: 0 16px;
    font-size: 14px;
  }

  .tool-buttons {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 0 16px;

    .n-button {
      justify-content: flex-start;
      height: 40px;
      font-size: 14px;
    }
  }

  .breadcrumb-section {
    padding: 0 16px;
  }
}


</style>
